<?php
namespace notification\tools;

use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Text;

use AlibabaCloud\SDK\Dingtalk\Voauth2_1_0\Dingtalk;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dingtalk\Voauth2_1_0\Models\GetAccessTokenRequest;

class DingdingNotification implements NotificationInterface {

    protected $client;

    protected $appkey = "";
    protected $appsecret = "";
    protected $agent_id = "";

    public function __construct($appkey, $appsecret, $agent_id) {
        $this->appkey = $appkey;
        $this->appsecret = $appsecret;                  
        $this->agent_id = $agent_id;                  
    }

    public function getAccessToken(){
        // 读取缓存
        $cache = cache('dingding_access_token');
        if($cache){
            return $cache;
        }
        $url = sprintf("https://oapi.dingtalk.com/gettoken?appkey=%s&appsecret=%s", $this->appkey, $this->appsecret);
        $httpClient = new \GuzzleHttp\Client();
        $response = $httpClient->get($url);
        $result = json_decode($response->getBody()->getContents(), true);

        // 写入缓存
        cache('dingding_access_token', $result, $result['expires_in'] - 1000);
        return $result;
    }


    /**
     * 使用 Token 初始化账号Client
     * @return Dingtalk Client
     */
    public static function createClient(){
        $config = new Config([]);
        $config->protocol = "https";
        $config->regionId = "central";
        return new Dingtalk($config);
    }



    public function sendText($message, $recipient) {

        // 实现邮件发送逻辑
        $result = $this->getAccessToken();
        $url = 'https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=' . $result['access_token'];
        $data = [
            "msg" => [
                "markdown" => [
                    "text" => $message->content,
                    "title" => $message->title
                ],
                "msgtype" => "markdown"
            ],
            "to_all_user" => "false",
            "agent_id" => $this->agent_id,
            "userid_list" => $recipient
        ];

        $httpClient = new \GuzzleHttp\Client();
        $response = $httpClient->request('POST', $url, [
            'json' => $data
        ]);
        $result = json_decode($response->getBody()->getContents(), true);
        // dump($result);
        return $result;
    }
}

